local lipan = fk.CreateSkill {
  name = "lipan",
}

lipan:addEffect( fk.EventPhaseEnd, {
  anim_type = "drawcard",
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Finish
  end,
  on_cost = function(self, event, target, player, data)
    local kingdoms = {"Cancel", "wei", "shu", "wu", "qun", "jin"}
    local choices = table.simpleClone(kingdoms)
    table.removeOne(choices, player.kingdom)
    local choice = player.room:askForChoice(player, choices, self.name, "#lipan-invoke", false, kingdoms)
    if choice ~= "Cancel" then
      event:setCostData(self,choice)
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:changeKingdom(player, event:getCostData(self), true)
    local tos = table.filter(room:getOtherPlayers(player, false), function(p) return p.kingdom == player.kingdom end)
    if #tos > 0 then
      player:drawCards(#tos, self.name)
    end
    if not player.dead then
      player:gainAnExtraPhase(Player.Play, true)
    end
  end,
})
lipan:addEffect( fk.EventPhaseEnd, {
  mute = true,
  can_trigger = function(self, event, target, player, data)
    return target == player and player.phase == Player.Play and player:usedSkillTimes("lipan", Player.HistoryTurn) > 0 and
      table.find(player.room:getOtherPlayers(player, false), function(p) return p.kingdom == player.kingdom and not p:isNude() end)
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room = player.room
    for _, p in ipairs(room:getOtherPlayers(player)) do
      if player.dead then return end
      if p.kingdom == player.kingdom and not p:isNude() and not p.dead then
        local card = room:askForCard(p, 1, 1, true, "lipan", true, ".", "#lipan-duel::"..player.id)
        if #card > 0 then
          room:useVirtualCard("duel", card, p, player, "lipan")
        end
      end
    end
  end,
})
return lipan